//
//  BDInviteFriendsViewController.m
//  BadBoy
//
//  Created by wen on 2017/8/23.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDInviteFriendsViewController.h"
#import "BDUserModel.h"
#import "UIButton+WebCache.h"
#import "BDUserInfoViewController.h"

@interface BDInviteFriendsViewController () 
{
    BOOL clickGetButton;
    UIColor *finishColor;
}

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UITextField *validationTextField;
@property (nonatomic, strong) UIButton *getCodeButton;
@property (nonatomic, strong) UIButton *invitationButton;
@property (nonatomic, strong) UIButton *revealButton;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *invitedRecordView;

@property (nonatomic, strong) BDUserModel *parentUser;
@property (nonatomic, strong) NSMutableArray *childrenArray;

@end

@implementation BDInviteFriendsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"邀请好友");
    
    _childrenArray = [NSMutableArray array];
    
    _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0)];
    _contentView.backgroundColor = [UIColor whiteColor];
    
    UIView *textFieldView = [[UIView alloc] initWithFrame:CGRectMake(10, 20, kBDScreenWidth - 20, 45)];
    textFieldView.layer.cornerRadius = 5;
    textFieldView.layer.masksToBounds = YES;
    textFieldView.layer.borderColor = [UIColor colorWithHexString:@"#cccccc"].CGColor;
    textFieldView.layer.borderWidth = 1.0;
    textFieldView.clipsToBounds = YES;
    [_contentView addSubview:textFieldView];
    
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 70, 15)];
    leftLabel.text = ASLocalizedString(@"手机号码");
    leftLabel.font = [UIFont systemFontOfSize:15];
    leftLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
    [textFieldView addSubview:leftLabel];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(80, 0, kBDScreenWidth - 20 - 80 - 80, 45)];
    _textField.borderStyle = UITextBorderStyleNone;
    _textField.placeholder = ASLocalizedString(@"请输入邀请好友手机号码");
    _textField.keyboardType = UIKeyboardTypeNumberPad;
    _textField.font = [UIFont systemFontOfSize:13];
    [textFieldView addSubview:self.textField];
    
    _getCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _getCodeButton.size = CGSizeMake(80, 45);
    _getCodeButton.right = textFieldView.width;
    _getCodeButton.backgroundColor = KBDColorBlue;
    [_getCodeButton setTitle:ASLocalizedString(@"获取验证码")forState:UIControlStateNormal];
    _getCodeButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [textFieldView addSubview:_getCodeButton];
    
    UIView *validationView = [[UIView alloc] initWithFrame:CGRectMake(10,20 + 45 + 10, kBDScreenWidth - 20, 45)];
    validationView.layer.cornerRadius = 5;
    validationView.layer.masksToBounds = YES;
    validationView.layer.borderColor = [UIColor colorWithHexString:@"#cccccc"].CGColor;
    validationView.layer.borderWidth = 1.0;
    [_contentView addSubview:validationView];
    
    UILabel *validationLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 70, 15)];
    validationLabel.text = ASLocalizedString(@"验证码");
    validationLabel.font = [UIFont systemFontOfSize:15];
    validationLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
    [validationView addSubview:validationLabel];
    
    _validationTextField = [[UITextField alloc] initWithFrame:CGRectMake(80, 0, kBDScreenWidth - 20 - 80, 45)];
    _validationTextField.borderStyle = UITextBorderStyleNone;
    _validationTextField.placeholder = ASLocalizedString(@"请输入邀请好友手机号码");
    _validationTextField.font = [UIFont systemFontOfSize:13];
    _validationTextField.keyboardType = UIKeyboardTypeNumberPad;
    [validationView addSubview:self.validationTextField];
    
    
    _invitationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _invitationButton.top = validationView.bottom + 10;
    _invitationButton.left = 10;
    _invitationButton.size = CGSizeMake(kBDScreenWidth - 20, 45);
    _invitationButton.layer.cornerRadius = 5;
    _invitationButton.backgroundColor = KBDColorBlue;
    [_invitationButton setTitle:ASLocalizedString(@"确    定")forState:UIControlStateNormal];
    [_contentView addSubview:_invitationButton];
    
    [self requestDatasource];
    
    [self bindRAC];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)requestDatasource{
    [MBManager showLoadingAlert:@"" clickHidden:NO clickBlock:nil];
    NSString *url = [NSString stringWithFormat:@"%@MLMRelates", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    [_childrenArray removeAllObjects];
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        NSArray *chData = x[@"children"][@"list"];
        for (NSDictionary *dic in chData) {
            BDUserModel *user = [BDUserModel mj_objectWithKeyValues:dic[@"children"]];
            [_childrenArray addObject:user];
        }
        NSArray *paData = x[@"parent"];
        if (paData.count) {
            NSDictionary *dic = paData.firstObject;
            _parentUser = [BDUserModel mj_objectWithKeyValues:dic[@"parent"]];
        }
        [MBManager hideAlert];
        [self updata];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [MBManager hideAlert];
        [self showErrorViewWithTapBlock:^{
            [self requestDatasource];
        }];
    }];
}

- (void)updata{
    
    self.invitedRecordView.top = _invitationButton.bottom;
    if (_parentUser != nil || _childrenArray.count != 0) {
        
        UILabel *recordLabel = [_invitedRecordView viewWithTag:2100];
        if (recordLabel == nil) {
            recordLabel = [[UILabel alloc] init];
            recordLabel.tag = 2100;
            [_invitedRecordView addSubview:recordLabel];
        }
        recordLabel.text = ASLocalizedString(@"邀请记录");
        recordLabel.font = [UIFont systemFontOfSize:12];
        recordLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        recordLabel.top = 30;
        recordLabel.size = CGSizeMake(50, 12);
        recordLabel.centerX = self.view.centerX;
        
        
        UIView *leftLine = [_invitedRecordView viewWithTag:2101];
        if (leftLine == nil) {
            leftLine = [[UILabel alloc] init];
            leftLine.tag = 2101;
            [_invitedRecordView addSubview:leftLine];
        }
        leftLine.top = recordLabel.top + 5;
        leftLine.left = 20;
        leftLine.size = CGSizeMake(recordLabel.left - 30, 0.5);
        leftLine.backgroundColor = [UIColor colorWithHexString:@"#767676"];
        
        
        UIView *rightLine = [_invitedRecordView viewWithTag:2102];
        if (rightLine == nil) {
            rightLine = [[UILabel alloc] init];
            rightLine.tag = 2102;
            [_invitedRecordView addSubview:rightLine];
        }
        rightLine.top = recordLabel.top + 5;
        rightLine.left = recordLabel.right + 10;
        rightLine.size = CGSizeMake(recordLabel.left - 30, 0.5);
        rightLine.backgroundColor = [UIColor colorWithHexString:@"#767676"];
        
        
        CGFloat margin = 20;
        CGFloat spacingX = 20;
        CGFloat spacingY =20;
        CGFloat buttonMidHeight = 8;
        NSInteger perRowCount = 5;
        CGFloat buttonTitleFontSize = 13;
        CGFloat inviterButtonWidth = (kBDScreenWidth - margin * 2 - spacingX * (perRowCount - 1)) / perRowCount;
        CGFloat inviterButtonHeight = inviterButtonWidth + buttonMidHeight + buttonTitleFontSize + 1;
        CGFloat endBottom = recordLabel.bottom;
        
        if (_parentUser) {
            UILabel *invitationLabel = [_invitedRecordView viewWithTag:2110];
            if (invitationLabel == nil) {
                invitationLabel = [[UILabel alloc] init];
                invitationLabel.tag = 2110;
                [_invitedRecordView addSubview:invitationLabel];
            }
            invitationLabel.text = ASLocalizedString(@"邀请我的好友：");
            invitationLabel.font = [UIFont systemFontOfSize:13];
            invitationLabel.textColor = [UIColor colorWithHexString:@"#767676"];
            invitationLabel.top = recordLabel.bottom + 20;
            invitationLabel.left = 10;
            invitationLabel.size = CGSizeMake(100, 13);
            
            
            UIButton *beInvitedButton = [_invitedRecordView viewWithTag:2111];
            if (beInvitedButton == nil) {
                beInvitedButton = [UIButton buttonWithType:UIButtonTypeCustom];
                beInvitedButton.tag = 2111;
                [_invitedRecordView addSubview:beInvitedButton];
            }
            beInvitedButton.size = CGSizeMake(inviterButtonWidth, inviterButtonHeight);
            beInvitedButton.imageFrame = [NSValue valueWithCGRect:CGRectMake(0, 0, inviterButtonWidth, inviterButtonWidth)];
            beInvitedButton.titleFrame = [NSValue valueWithCGRect:CGRectMake(0, inviterButtonHeight - buttonTitleFontSize - 1, inviterButtonWidth, buttonTitleFontSize + 1)];
            [beInvitedButton sd_setImageWithURL:[NSURL URLWithString:_parentUser.cover] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"cover"]];
            [beInvitedButton setTitle:_parentUser.nickname forState:UIControlStateNormal];
            [beInvitedButton setTitleColor:[UIColor colorWithHexString:@"#808080"] forState:UIControlStateNormal];
            beInvitedButton.titleLabel.font = [UIFont systemFontOfSize:12];
            beInvitedButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
            beInvitedButton.titleLabel.textAlignment = NSTextAlignmentCenter;
            beInvitedButton.imageView.layer.masksToBounds = YES;
            beInvitedButton.imageView.layer.cornerRadius = inviterButtonWidth / 2.0;
            beInvitedButton.contentMode = UIViewContentModeScaleAspectFit;
            beInvitedButton.left = 20;
            beInvitedButton.top = invitationLabel.bottom + 15;
            
            
            [[beInvitedButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                [self clickUser:_parentUser];
            }];
            endBottom = beInvitedButton.bottom;
        }
        
        if (_childrenArray.count) {
            UILabel *myDetermineLabel = [_invitedRecordView viewWithTag:2120];
            if (myDetermineLabel == nil) {
                myDetermineLabel = [[UILabel alloc] init];
                myDetermineLabel.tag = 2120;
                [_invitedRecordView addSubview:myDetermineLabel];
            }
            myDetermineLabel.left = 10;
            myDetermineLabel.top = endBottom + 20;
            myDetermineLabel.size = CGSizeMake(100, 13);
            myDetermineLabel.font = [UIFont systemFontOfSize:13];
            myDetermineLabel.text = ASLocalizedString(@"我邀请的好友：");
            myDetermineLabel.textColor = [UIColor colorWithHexString:@"#767676"];
            
            
            for (int i = 0; i < _childrenArray.count; i++) {
                if (i < perRowCount * 2) {
                    BDUserModel *child = _childrenArray[i];
                    
                    UIButton *invitersButton = [_invitedRecordView viewWithTag:2121 + i];
                    if (invitersButton == nil) {
                        invitersButton = [UIButton buttonWithType:UIButtonTypeCustom];
                        invitersButton.tag = 2121 + i;
                        [_invitedRecordView addSubview:invitersButton];
                    }
                    invitersButton.size = CGSizeMake(inviterButtonWidth, inviterButtonHeight);
                    invitersButton.imageFrame = [NSValue valueWithCGRect:CGRectMake(0, 0, inviterButtonWidth, inviterButtonWidth)];
                    invitersButton.titleFrame = [NSValue valueWithCGRect:CGRectMake(0, inviterButtonHeight - buttonTitleFontSize - 1, inviterButtonWidth, buttonTitleFontSize + 1)];
                    [invitersButton sd_setImageWithURL:[NSURL URLWithString:child.cover] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"cover"]];
                    [invitersButton setTitle:child.nickname forState:UIControlStateNormal];
                    [invitersButton setTitleColor:[UIColor colorWithHexString:@"#808080"] forState:UIControlStateNormal];
                    invitersButton.titleLabel.font = [UIFont systemFontOfSize:12];
                    invitersButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
                    invitersButton.titleLabel.textAlignment = NSTextAlignmentCenter;
                    invitersButton.imageView.layer.masksToBounds = YES;
                    invitersButton.imageView.layer.cornerRadius = inviterButtonWidth / 2.0;
                    invitersButton.contentMode = UIViewContentModeScaleAspectFit;
                    
                    invitersButton.top = myDetermineLabel.bottom + 20 + (i / perRowCount) * (inviterButtonHeight + spacingY);
                    invitersButton.left = margin + (i % perRowCount) * (inviterButtonWidth + spacingX);
                    
                    endBottom = invitersButton.bottom;
                    
                    [[invitersButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                        [self clickUser:_childrenArray[i]];
                    }];
                }
            }
            
            if (_childrenArray.count > perRowCount * 2) {
                self.revealButton.top = endBottom + 20;
                _revealButton.size = CGSizeMake(100, 30);
                _revealButton.centerX = self.view.centerX;
                [_revealButton setTitle:ASLocalizedString(@"显示全部 >>")forState:UIControlStateNormal];
                _revealButton.titleLabel.font = [UIFont systemFontOfSize:13];
                [_revealButton setTitleColor:KBDColorBlue forState:UIControlStateNormal];
                endBottom = _revealButton.bottom;
            }
        }
        _invitedRecordView.height = endBottom + 20;
    }else{
        _invitedRecordView.height = 0;
    }
    
    _contentView.height = _invitedRecordView.bottom;
    _contentView.top = 10;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight)];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_scrollView];
    
    [_scrollView addSubview:_contentView];
    
    _scrollView.contentSize = CGSizeMake(0, _contentView.bottom);
}

- (void)bindRAC{
    //发送验证短信
    //绑定发送验证码button是否可以点击和背景颜色
    RACSignal *getEnable = [RACSignal combineLatest:@[self.textField.rac_textSignal] reduce:^id _Nullable{
        return @(self.textField.text.length == 11);
    }];
    RAC(self.getCodeButton, userInteractionEnabled) = getEnable;
    [getEnable subscribeNext:^(id  _Nullable x) {
        if (clickGetButton == NO) {
            self.getCodeButton.backgroundColor = [x boolValue] ? kCodeButtonColor : kNOValidColor;
        }else{
            finishColor = [x boolValue] ? kCodeButtonColor : kNOValidColor;
        }
    }];
    
    //发送验证码
    [[self.getCodeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        // BDLog(ASLocalizedString(@"点击了发送验证的按钮"));
        clickGetButton = YES;
        self.getCodeButton.backgroundColor = kNOValidColor;
        _getCodeButton.userInteractionEnabled = NO;
        
        NSDictionary *para = @{@"mobile":self.textField.text};
        NSString *url = [NSString stringWithFormat:@"%@sms", KBDBaseURL];
        
        RACCommand *getCodeCommand = [BDNetworkingServer yy_POST:url parameters:para validation:nil automaticProcessingError:NO];
        RACSignal *getCodeSignal = [getCodeCommand execute:nil];
        
        [[getCodeSignal deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id  _Nullable x) {
            [self.validationTextField becomeFirstResponder];
            
            @weakify(self);
            __block NSInteger number = 60;
            NSInteger numberLimit = number;
            RACSignal *timeSignal = [[[[[RACSignal interval:1.0f onScheduler:[RACScheduler mainThreadScheduler]] take:numberLimit] startWith:[NSDate date]] map:^id(NSDate *date) {
                @strongify(self);
                if (number == 0) {
                    [self.getCodeButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
                    self.getCodeButton.userInteractionEnabled = YES;
                    clickGetButton = NO;
                    self.getCodeButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
                    return @YES;
                }else{
                    [self.getCodeButton setTitle:[NSString stringWithFormat:ASLocalizedString(@"剩余%ld秒"), number] forState:UIControlStateNormal];
                    //                    // BDLog(ASLocalizedString(@"按钮文本是什么：%@"), [NSString stringWithFormat:ASLocalizedString(@"剩余%ld秒"), number]);
                    number--;
                    return @NO;
                }
            }] takeUntil:self.rac_willDeallocSignal];
            
            _getCodeButton.rac_command = [[RACCommand alloc]initWithEnabled:timeSignal signalBlock:^RACSignal *(id input) {
                number = numberLimit;
                return timeSignal;
            }];
        }];
        //错误处理
        [getCodeSignal subscribeError:^(NSError * _Nullable error) {
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:ASLocalizedString(@"发送验证码失败，请稍后再试")clickHidden:NO clickBlock:nil];
            [_getCodeButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
            _getCodeButton.userInteractionEnabled = YES;
            clickGetButton = NO;
            _getCodeButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
        }];
    }];

    
    //确定发送邀请
    [[_invitationButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (self.textField.text.length != 11) {
            [MBManager showBriefAlert:ASLocalizedString(@"请填写正确的手机号")clickHidden:YES clickBlock:nil];
            return;
        }
        if (self.validationTextField.text.length == 0) {
            [MBManager showBriefAlert:ASLocalizedString(@"请填写被邀请人收到的验证码")clickHidden:YES clickBlock:nil];
            return;
        }
        
        //18609497416   8279
        
        [MBManager showLoadingAlert:@"" clickHidden:NO clickBlock:nil];
        
        NSString *url = [NSString stringWithFormat:@"%@MLMRelates", KBDBaseURL];
        NSString *headValid = [BDUserModel getHeaderValidation];
        NSDictionary *para = @{@"mobile":self.textField.text,
                               @"code":self.validationTextField.text};
        
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            [MBManager hideAlert];
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"邀请成功")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:ASLocalizedString(@"邀请失败")clickHidden:YES clickBlock:nil];
        }];
        
    }];
    
    //显示更多
    [[_revealButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
    }];
}

- (void)clickUser:(BDUserModel *)user{
    BDUserInfoViewController *infoViewController = [[BDUserInfoViewController alloc] initWithUserID:user.user_id isFollow:NO guanzhuBlock:nil];
    [self.navigationController pushViewController:infoViewController animated:YES];
}

- (UIView *)invitedRecordView{
    if (!_invitedRecordView) {
        self.invitedRecordView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0)];
        _invitedRecordView.backgroundColor = [UIColor whiteColor];
        [_contentView addSubview:_invitedRecordView];
    }
    return _invitedRecordView;
}

- (UIButton *)revealButton{
    if (!_revealButton) {
        self.revealButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_invitedRecordView addSubview:_revealButton];
    }
    return _revealButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
